package com.yinchuang.aiuidemo;

import android.media.AudioRecord;
import android.util.Log;

/**
 * Created by lingchen on 2019/5/28. 11:17
 * mail:lingchen52@foxmail.com
 */
public class MyRecorder implements Runnable {

    private static MyRecorder sRecorder = null;
    private RecorderListener mRecorderListener;
    private AudioRecord mAudioRecord = null;
    private byte[] mbuffer;
    private boolean isRecord;
    private int mBufferSizeInBytes;

    public MyRecorder() {

    }

    public static MyRecorder getInstance() {
        if (sRecorder == null) {
            sRecorder = new MyRecorder();
            sRecorder.isRecord = false;
        }

        return sRecorder;
    }

    public int initRecoder(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat) {
        int bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat) * 10;
        mBufferSizeInBytes = bufferSizeInBytes;
        if (-2 == bufferSizeInBytes) {
            return -2;
        } else if (mAudioRecord != null) {
            return -1;
        } else {
            mbuffer = new byte[bufferSizeInBytes];
            mAudioRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes);
            return 0;
        }
    }

    public void startRecoder(RecorderListener listener) {
        Log.d("MainActivity", "mAudioRecord.startRecording()");
        mRecorderListener = listener;
        if (!isRecord) {
            isRecord = true;
            mAudioRecord.startRecording();
            new Thread(this).start();
        }
    }

    public boolean isRun() {
        return isRecord;
    }

    public void stopRecorder() {
        mAudioRecord.stop();
        isRecord = false;
    }

    @Override
    public void run() {
        Log.d("MainActivity", "run");
        while (isRecord) {
            Log.d("MainActivity", "run" + isRecord);
            int realsize = mAudioRecord.read(mbuffer, 0, mBufferSizeInBytes);
            mRecorderListener.OnReceiveBytes(mbuffer, realsize);
        }
    }

}
